<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="请选择用户" prop="userId">
        <el-select v-model="formData.userId" filterable placeholder="请选择用户">
          <!-- bugfix: Change to self-closing tags -->
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="个人账号" prop="myAccount">
        <el-input v-model="formData.myAccount" placeholder="请输入个人账号" />
      </el-form-item>
      <el-form-item label="状态" prop="defaultStatus">
        <el-radio-group v-model="formData.defaultStatus">
          <el-radio value="1">缴存</el-radio>
          <el-radio value="2">提取</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="中心编号" prop="centerNumber">
        <el-input v-model="formData.centerNumber" placeholder="请输入中心编号" />
      </el-form-item>
      <el-form-item label="中心名称" prop="centerName">
        <el-input v-model="formData.centerName" placeholder="请输入中心名称" />
      </el-form-item>
      <el-form-item label="单位名称" prop="companyNumber">
        <el-input v-model="formData.companyNumber" placeholder="请输入单位名称" />
      </el-form-item>
      <el-form-item label="单位账号" prop="companyAccount">
        <el-input v-model="formData.companyAccount" placeholder="请输入单位账号" />
      </el-form-item>
      <el-form-item label="个人缴存比例" prop="myRatio">
        <el-input v-model="formData.myRatio" placeholder="请输入个人缴存比例" />
      </el-form-item>
      <el-form-item label="单位缴存比例" prop="companyRatio">
        <el-input v-model="formData.companyRatio" placeholder="请输入单位缴存比例" />
      </el-form-item>
      <el-form-item label="个人缴存基数" prop="myBaseNumber">
        <el-input v-model="formData.myBaseNumber" placeholder="请输入个人缴存基数" />
      </el-form-item>
      <el-form-item label="个人月缴存额" prop="myAmount">
        <el-input v-model="formData.myAmount" placeholder="请输入个人月缴存额" />
      </el-form-item>
      <el-form-item label="单位月缴存额" prop="companyAmount">
        <el-input v-model="formData.companyAmount" placeholder="请输入单位月缴存额" />
      </el-form-item>
      <el-form-item label="存取日期" prop="saveDate">
        <el-date-picker
          v-model="formData.saveDate"
          type="date"
          value-format="x"
          placeholder="选择存取日期"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { FundApi, FundVO } from '@/api/member/fund'
import * as UserApi from '@/api/member/user'

/** 会员公积金 表单 */
defineOptions({ name: 'FundForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined,
  myAccount: undefined,
  defaultStatus: undefined,
  accountBalance: undefined,
  centerNumber: undefined,
  centerName: undefined,
  companyNumber: undefined,
  companyAccount: undefined,
  myRatio: undefined,
  companyRatio: undefined,
  myBaseNumber: undefined,
  myAmount: undefined,
  companyAmount: undefined,
  saveDate: undefined
})
const formRules = reactive({
  userId: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
  myAccount: [{ required: true, message: '个人账号不能为空', trigger: 'blur' }],
  defaultStatus: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  accountBalance: [{ required: true, message: '账户余额不能为空', trigger: 'blur' }],
  centerNumber: [{ required: true, message: '中心编号不能为空', trigger: 'blur' }],
  centerName: [{ required: true, message: '中心名称不能为空', trigger: 'blur' }],
  companyNumber: [{ required: true, message: '单位名称不能为空', trigger: 'blur' }],
  companyAccount: [{ required: true, message: '单位账号不能为空', trigger: 'blur' }],
  myRatio: [
    { required: true, message: '个人缴存比例不能为空', trigger: 'blur' },
    {
      pattern: /^\d{1,2}$|^100$/,
      message: '个人缴存比例必须是 0 - 100 的整数',
      trigger: 'blur'
    }
  ],
  companyRatio: [
    { required: true, message: '单位缴存比例不能为空', trigger: 'blur' },
    {
      pattern: /^\d{1,2}$|^100$/,
      message: '单位缴存比例必须是 0 - 100 的整数',
      trigger: 'blur'
    }
  ],
  myBaseNumber: [{ required: true, message: '个人缴存基数不能为空', trigger: 'blur' }],
  myAmount: [{ required: true, message: '个人月缴存额不能为空', trigger: 'blur' }],
  companyAmount: [{ required: true, message: '单位月缴存额不能为空', trigger: 'blur' }],
  saveDate: [{ required: true, message: '存取日期不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await FundApi.getFund(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as FundVO
    if (formType.value === 'create') {
      await FundApi.createFund(data)
      message.success(t('common.createSuccess'))
    } else {
      await FundApi.updateFund(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    myAccount: undefined,
    defaultStatus: undefined,
    accountBalance: undefined,
    centerNumber: undefined,
    centerName: undefined,
    companyNumber: undefined,
    companyAccount: undefined,
    myRatio: undefined,
    companyRatio: undefined,
    myBaseNumber: undefined,
    myAmount: undefined,
    companyAmount: undefined,
    saveDate: undefined
  }
  formRef.value?.resetFields()
}


onMounted(() => {
  handleQuery()
})

const userOptions = ref([])

const userQueryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  nickname: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: null,
  groupId: null
})

/** 搜索按钮操作 */
const handleQuery = () => {
  userQueryParams.pageNo = 1
  getUserList()
}

/** 查询列表 */
const getUserList = async () => {
  try {
    const data = await UserApi.getUserPage(userQueryParams)
    userOptions.value = data.list.map((item) => ({
      label: item.nickname,
      value: item.id
    }))
  } finally {
    console.log('获取用户列表失败')
  }
}

</script>